/**
 * This file is Copyright © 2008 Software Craftsmen Limited. All Rights Reserved.
 */
package com.softwarecraftsmen.cachecontrol.caches;

import com.softwarecraftsmen.cachecontrol.keys.AbstractKey;
import com.softwarecraftsmen.cachecontrol.keys.Key;
import com.softwarecraftsmen.cachecontrol.*;
import org.jetbrains.annotations.NotNull;

public abstract class AbstractComptrolledCache<V> implements ComptrolledCache<V>
{
	private final Key<V> identifier;

	public AbstractComptrolledCache(@NotNull final Key<V> identifier)
	{
		this.identifier = identifier;
	}

	public boolean equals(final Object o)
	{
		if (this == o)
		{
			return true;
		}
		if (!(this.getClass().equals(o.getClass())))
		{
			return false;
		}

		final AbstractComptrolledCache that = (AbstractComptrolledCache) o;

		return identifier.equals(that.identifier);
	}

	public int hashCode()
	{
		return identifier.hashCode();
	}

	public String toString()
	{
		return SafeStringFormatter.format("%1$s(%2$s)", getClass().getSimpleName(), identifier);
	}

	public final @NotNull Key<V> identifier()
	{
		return identifier;
	}

	public abstract @NotNull
	Item<V> obtain(@NotNull final Key<V> key);

	@SuppressWarnings("unchecked")
	public final @NotNull Item<V> obtain(@NotNull final Object... orderedKeyComponents)
	{
		Key<V> key = AbstractKey.createKey(orderedKeyComponents);
		return obtain(key);
	}

	@NotNull
	public abstract Item<V> store(final @NotNull Key<V> vKey, final @NotNull V value);

	@NotNull
	public Value<V> put(final @NotNull V value)
	{
		return new Value<V>(this, value);
	}

	@NotNull
	public CacheAndKey<V> at(@NotNull final Object... orderedKeyComponents)
	{
		return new CacheAndKey<V>(this, AbstractKey.<V>createKey(orderedKeyComponents));
	}
}
